%%%-------------------------------------------------------------------
%%% @author liuwentao
%%% @doc
%%%     道具信息
%%% @end
%%% Created : 19. 7月 2021 17:04
%%%-------------------------------------------------------------------
-module(item).
-author("liuwentao").

-export([
    login/1
    , make/1
    , make/3
%%    , use_normal/4
%%    , do_use_normal/4
%%    , use_normal_batch/4
%%    , do_use_normal_batch/4
%%    , check_expire/1
%%    , check_expire/2
%%    , check_start/1
%%    , attr/2
%%    , match/3
%%    , make_expire/3
%%    , match_update/2
%%    , make_cond/4
%%    , sell/3
%%    , set_extra_list/3
%%    , del_extra_list/2
%%    , find_extra_list/3
%%    , get_item_price/3
%%    , get_item_name/1
%%    , item_compose/5
%%    , diff_item_assets/3
%%    , buy_item/3
%%    , merge_same_item/1
%%    , merge_same_item/2
%%    , filter_same_item/1
%%    , filter_zero_item/1
%%    , auto_buy_pellet/3
%%    , filter_classes_item/3
%%    , double_reward/3
%%    , send_reward/2
%%    , send_reward/4
%%    , send_reward/5
%%    , check_class_id/3
%%    , item_compose/4
%%    , send_reward_no_notice/2
%%    , send_reward_no_notice/4
%%    , get_item_num/2
%%    %% 物品通知
%%    , alert_reward/1
%%    , alert_reward/2
%%    , alert_reward/3
%%    %% 物品通知(不合并)
%%    , alert_reward_no_merge/1
%%    , alert_reward_no_merge/2
%%    , alert_reward_no_merge/3
%%    , merge_reward/1
%%    , to_quality_name/1
]).
-include("item.hrl").
-include("role.hrl").
-include("condition.hrl").
-include("common.hrl").
-include("package.hrl").
-include("trigger.hrl").

%% @doc 登陆检测过期物品,仅需检测
-spec login(Role :: #role{}) -> {ok, NewRole :: #role{}}.
login(Role = #role{}) ->
    {ok, Role}.


%% @doc 生成一个物品
-spec make(BaseId :: pos_integer(), Bind :: 1, Quantity :: pos_integer()) -> false | {ok, [Item :: #item{}]}.
make(_BaseId, _Bind, 0) -> false;
make(BaseId, Bind, Quantity) ->
    make(#{base_id => BaseId, bind => Bind, quantity => Quantity}).
make([], Items) -> {ok, Items};
make([H | Rest], Items) ->
    NewItems = case make(H) of
                   {ok, AddItems} ->
                       AddItems ++ Items;
                   _ -> Items
               end,
    make(Rest, NewItems).
make({BaseId, Bind, Quantity}) ->
    make(#{base_id => BaseId, bind => Bind, quantity => Quantity});
make(Item = #item{}) -> {ok, [Item]};
make(Args = #{base_id := BaseId, bind := Bind, quantity := Quantity}) ->
    case item_data:get(BaseId) of
        #item_base{type = ?item_type_numeric} ->
            ?ERR("错误的道具发放[BaseId:~w] From:~w", [BaseId, util:get_stacktrace()]),
            false;
        #item_base{quality = Quality, group = ItemGroup, type = Type, use_type = UseType, condition = Condition, overlap = OverLap, expire_type = OldExpireType, expire_time = OldExpireTime, lev = Lev, classes = Classes, sex = Sex, need_identify = NeedIdentify} ->
            IsIdentify = case NeedIdentify of
                             ?true ->
                                 ?false;
                             ?false ->
                                 ?true
                         end,
            {_NewCond, ReLev, _ReClasses, ReSex} = make_cond(Lev, Classes, Sex, Condition),
            {ExpireType, ExpireTime} = make_expire(BaseId, OldExpireType, OldExpireTime),
            %% 品阶
            Step = case Args of
                       #{step := Step0} when is_integer(Step0) -> Step0;
                       _ -> 0
                   end,
            Item = #item{ver = ?item_ver, bind = Bind, group = ItemGroup, base_id = BaseId, quality = Quality, quantity = Quantity, type = Type, use_type = UseType, lev = ReLev, sex = ReSex, expire_type = ExpireType, expire_time = ExpireTime, create_time = date:unixtime(), step = Step, is_identify = IsIdentify},
            case Quantity =< OverLap of
                true ->
                    %% 根据不同类型对道具进行初始化
                    Item1 = item_type:recalc(Item),
                    {ok, [Item1]};
                false ->
                    make(Item#item{quantity = OverLap}, OverLap, Quantity, [])
            end;
        _Err ->
            false
    end;
make(ItemInfo) when is_list(ItemInfo) -> make(ItemInfo, []);
make(_Unkown) ->
    ?ERR("生成一个物品错误Err:~w", [_Unkown]),
    false.


%% @doc 大于堆叠数时产生物品
make(_BaseItem, _OverLap, 0, Items) ->
    {ok, Items};
make(BaseItem, OverLap, Quantity, Items)
    when Quantity >= OverLap ->
    %% 根据不同类型对道具进行初始化
    NewItem = item_type:recalc(BaseItem),
    %% 重新计算道具的属性
    make(BaseItem, OverLap, Quantity - OverLap, [NewItem | Items]);
make(BaseItem, OverLap, Quantity, Items)
    when OverLap > Quantity ->
    %% 根据不同类型对道具进行初始化
    NewItem = item_type:recalc(BaseItem#item{quantity = Quantity}),
    %% 重新计算道具的属性
    make(BaseItem, OverLap, 0, [NewItem | Items]).



%%%% @doc 使用普通物品
%%-spec use_normal(Role :: #role{}, Item :: #item{}, ItemBase :: #item_base{}, Num :: pos_integer()) ->
%%    {false, Reason :: bitstring()} | {ok, NewRole :: #role{}}.
%%use_normal(Role, _Item, ItemBase = #item_base{effect = Effect}, Num) ->
%%    case do_use_normal(Effect, Num, ItemBase, Role) of
%%        {ok, NewRole} ->
%%            item_effect:msg(ItemBase, Num, NewRole),
%%            {ok, NewRole};
%%        {false, Reason} ->
%%            {false, Reason}
%%    end.
%%
%%
%%use_normal_batch(Role, _Item, ItemBase = #item_base{effect = Effect}, Num) ->
%%    case do_use_normal_batch(Effect, Num, ItemBase, Role) of
%%        {ok, NewRole} ->
%%            item_effect:msg(ItemBase, Num, NewRole),
%%            {ok, NewRole};
%%        {false, Reason} ->
%%            {false, Reason}
%%    end.
%%
%%
%%%% @doc 检测物品现在是否过期
%%-spec check_expire(Item :: #item{}) -> true | false.
%%check_expire(#item{expire_type = ?item_expire_null}) -> false;
%%check_expire(#item{expire_type = ?item_expire_startdate}) -> false;
%%check_expire(#item{expire_type = ?item_expire_starttime}) -> false;
%%check_expire(#item{expire_type = ?item_expire_puton_enddate}) -> false;
%%check_expire(#item{expire_type = ?item_expire_puton_endtime}) -> false;
%%check_expire(#item{base_id = BaseId, expire_time = 0}) ->
%%    ?ERR("[~w]的过期时间设置错误", [BaseId]),
%%    false;
%%check_expire(#item{expire_time = EndTime}) ->
%%    Now = date:unixtime(),
%%    Now >= EndTime.
%%
%%%% @doc 检测物品过期时间是否超过指定时间
%%-spec check_expire(Now :: pos_integer(), Item :: #item{}) -> true | false.
%%check_expire(_Now, #item{expire_type = ?item_expire_null}) -> false;
%%check_expire(_Now, #item{expire_type = ?item_expire_startdate}) -> false;
%%check_expire(_Now, #item{expire_type = ?item_expire_starttime}) -> false;
%%check_expire(_Now, #item{expire_type = ?item_expire_puton_enddate}) -> false;
%%check_expire(_Now, #item{expire_type = ?item_expire_puton_endtime}) -> false;
%%check_expire(_Now, #item{base_id = BaseId, expire_time = 0}) ->
%%    ?ERR("[~w]的过期时间设置错误", [BaseId]),
%%    false;
%%check_expire(Now, #item{expire_time = EndTime}) ->
%%    Now >= EndTime.
%%
%%%% @doc 检测物品现在是否开启
%%-spec check_start(Item :: #item{}) -> true | false.
%%check_start(#item{expire_type = ?item_expire_null}) -> true;
%%check_start(#item{expire_type = ?item_expire_enddate}) -> true;
%%check_start(#item{expire_type = ?item_expire_endtime}) -> true;
%%check_start(#item{expire_type = ?item_expire_puton_endtime}) -> true;
%%check_start(#item{expire_type = ?item_expire_puton_enddate}) -> true;
%%check_start(#item{base_id = BaseId, expire_time = 0}) ->
%%    ?ERR("[~w]的开启时间设置错误", [BaseId]),
%%    false;
%%check_start(#item{expire_time = StartTime}) ->
%%    Now = date:unixtime(),
%%    Now >= StartTime.
%%
%%%% @doc 获取物品基础信息
%%-spec attr(Atom, Item :: #item{} | pos_integer()) -> bitstring() | list() | non_neg_integer() when
%%    Atom :: name | set_id | base_attr | effect | group.
%%attr(name, #item{base_id = BaseId}) ->
%%    case item_data:get(BaseId) of
%%        #item_base{name = Name} -> Name;
%%        _ ->
%%            ?ERR("发现错误的道具,[~w]", [BaseId]),
%%            ?T("未知物体")
%%    end;
%%attr(name, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{name = Name} -> Name;
%%        _ ->
%%            ?ERR("发现错误的道具,[~w]", [BaseId]),
%%            ?T("未知物体")
%%    end;
%%attr(base_attr, #item{base_id = BaseId}) ->
%%    case item_data:get(BaseId) of
%%        #item_base{attr = Attr} -> Attr;
%%        _ -> []
%%    end;
%%attr(base_attr, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{attr = Attr} -> Attr;
%%        _ -> []
%%    end;
%%attr(effect, #item{base_id = BaseId}) ->
%%    case item_data:get(BaseId) of
%%        #item_base{effect = Effect} -> Effect;
%%        _ -> []
%%    end;
%%attr(effect, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{effect = Effect} -> Effect;
%%        _ -> []
%%    end;
%%attr(type, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{type = Type} -> Type;
%%        _ -> 0
%%    end;
%%attr(buy_source, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{buy_source = BuySource} -> BuySource;
%%        _ -> []
%%    end;
%%attr(quality, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{quality = Quality} -> Quality;
%%        _ -> 0
%%    end;
%%attr(use_type, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{use_type = UseType} -> UseType;
%%        _ -> ?item_use_not
%%    end;
%%attr(look_id, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{look_id = LookId} -> LookId;
%%        _ -> 0
%%    end;
%%attr(expire, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{expire_type = ExpireType, expire_time = ExpireTime} ->
%%            {ExpireType, ExpireTime};
%%        _ ->
%%            {0, 0}
%%    end;
%%attr(group, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{group = Group} -> Group;
%%        _ -> 0
%%    end;
%%attr(price, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{price = ItemVal} ->
%%            [ItemVal];
%%        _ ->
%%            []
%%    end;
%%attr(bind, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{bind = Bind} -> Bind;
%%        _ -> 0
%%    end;
%%attr(lev, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{lev = Lev} -> Lev;
%%        _ -> 0
%%    end;
%%attr(suit_id, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{suit_id = SuitId} ->
%%            SuitId;
%%        _ ->
%%            0
%%    end;
%%attr(change_classes, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{change_classes = L} ->
%%            L;
%%        _ ->
%%            []
%%    end;
%%attr(classes, #item{base_id = BaseId}) ->
%%    case item_data:get(BaseId) of
%%        #item_base{classes = L} ->
%%            L;
%%        _ ->
%%            0
%%    end;
%%attr(classes, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{classes = L} ->
%%            L;
%%        _ ->
%%            0
%%    end;
%%attr(diff_sex_id, BaseId) ->
%%    case item_data:get(BaseId) of
%%        #item_base{diff_sex_id = DiffSexId} ->
%%            DiffSexId;
%%        _ ->
%%            0
%%    end.
%%
%%%% @doc 匹配物品额外字段的属性
%%-spec match(ExtraVal :: pos_integer(), #item{}, DefaultVal :: non_neg_integer()) -> Val :: non_neg_integer().
%%match(_Err, _, Val) ->
%%    ?ERR("匹配不存在的字段:~w", [_Err]),
%%    Val.
%%
%%%% @doc 更新物品额外字段的属性
%%-spec match_update({pos_integer(), pos_integer() | bitstring()}, #item{}) -> #item{}.
%%match_update(_Err, Item) ->
%%    ?ERR("匹配更新不存在:~w", [_Err]),
%%    Item.
%%
%%%% -----------------------------------------------
%%%% 内部
%%%% -----------------------------------------------
%%
%%
%% 产生新的限制等级和职业
make_cond(Lev, Classes, Sex, Condition) ->
    {LevCond, NewLev} = case Lev >= 0 of
                            true -> {[#condition{label = lev, op = ge, val = Lev}], Lev};
                            false -> {[], 0}
                        end,
    {ClassesCond, NewClasses} = {[#condition{label = classes, op = include, val = Classes}], Classes},
    {SexCond, NewSex} = case Sex >= 0 andalso Sex =< 2 of
                            true -> {[#condition{label = sex, op = eq, val = Sex}], Sex};
                            false -> {[], 2}
                        end,
    {LevCond ++ ClassesCond ++ SexCond ++ Condition, NewLev, NewClasses, NewSex}.

%% 产生过期信息字段
make_expire(_, ?item_expire_null, 0) -> {0, 0};
make_expire(_BaseId, _, 0) ->
    ?ERR("[~w]的过期时间设置错误", [_BaseId]),
    {0, 0};
%% ============================
%% 穿戴判定 先置空时间,使用的时候再去读item表重新获取,
%% 穿戴判定-倒计时
make_expire(_BaseId, ?item_expire_puton_endtime, _Minute) ->
    {?item_expire_puton_endtime, 0};
%% 穿戴判定-指定日期
make_expire(_BaseId, ?item_expire_puton_enddate, _Data) ->
    {?item_expire_puton_enddate, 0};

%% 获得判定-倒计时
make_expire(_BaseId, ?item_expire_endtime, Minute) ->
    EndTime = date:unixtime() + Minute * 60,
    {?item_expire_endtime, EndTime};
make_expire(_BaseId, ?item_expire_starttime, Minute) ->
    StartTime = date:unixtime() + Minute * 60,
    {?item_expire_starttime, StartTime};
%% 获得判定-按照日期
make_expire(_BaseId, ?item_expire_enddate, {{Year, Month, Day}, {Hour, Minute, Seconds}}) ->
    case date:datetime_to_seconds({{Year, Month, Day}, {Hour, Minute, Seconds}}) of
        false ->
            ?ERR("[~w]的过期时间设置错误", [_BaseId]),
            {0, 0};
        End -> {?item_expire_enddate, End}
    end;
make_expire(_BaseId, ?item_expire_startdate, {{Year, Month, Day}, {Hour, Minute, Seconds}}) ->
    case date:datetime_to_seconds({{Year, Month, Day}, {Hour, Minute, Seconds}}) of
        false ->
            ?ERR("[~w]的开启时间设置错误", [_BaseId]),
            {0, 0};
        Start -> {?item_expire_startdate, Start}
    end;
make_expire(_BaseId, _, _) -> ?ERR("[~w]的过期时间设置错误", [_BaseId]).

%%
%%%%%% 执行使用
%%do_use_normal(_Effect, 0, _, Role) -> {ok, Role};
%%do_use_normal(Effect, Num, ItemBase, Role) ->
%%    ?DEBUG(":~w", [Effect]),
%%    case item_effect:do(Effect, ItemBase, Role) of
%%        {false, Reason} -> {false, Reason};
%%        {ok, NewRole} ->
%%            do_use_normal(Effect, Num - 1, ItemBase, NewRole)
%%    end.
%%
%%
%%do_use_normal_batch(_Effect = [{Type, Value} | _], Num, ItemBase, Role) ->
%%    List = [],
%%    case lists:member(Type, List) of
%%        true ->
%%            case item_effect:do([{Type, Value * Num}], ItemBase, Role) of
%%                {false, Reason} -> {false, Reason};
%%                {ok, NewRole} ->
%%                    {ok, NewRole}
%%            end;
%%        Other ->
%%            ?ERR("不是已记录的可以批量使用的物品类型：~w, {Type, Value} ~w", [Other, {Type, Value}]),
%%            {false, ?T("不是已记录的可以批量使用的物品类型")}
%%    end;
%%
%%do_use_normal_batch(_Effect = [_BadMatch | _], _Num, _ItemBase, _Role) ->
%%    ?DEBUG(":~w", [_BadMatch]),
%%    {false, ?T("批量使用的物品效果参数错误")}.
%%
%%%% @spec sell(ItemsInfo, BagCode, Role) -> {error, Msg}|{ok, Role1}
%%%% ItemsInfo = [{ItemId, ItemBid, Count}, ...] 贩卖物品信息
%%%% BagCode = 标签 bag
%%%% Role = #role{}
%%%% Msg = bitstring()
%%%% @doc 贩卖物品， 根据物品信息， 卖出得到石币或者金贝
%%sell([], _, _Role) ->
%%    {error, ?T("未发现贩卖物品")};
%%sell(ItemsInfo, _BagCode, Role = #role{p_bag = Bag}) ->
%%    ItemInfos2 = list_util:verify_uniq(ItemsInfo, 1),
%%    case ItemInfos2 of
%%        [{ItemId, _ItemBid, Count}] ->
%%            case package:find(by_id, ItemId, Bag) of
%%                false ->
%%                    {error, ?T("未发现该物品")};
%%                {ok, Item = #item{bind = 0, base_id = ItemBid}} ->
%%                    case sell_check(Item) of
%%                        {ok} ->
%%                            [ItemVal] = attr(price, ItemBid),
%%                            case sell_by_market(Role, ItemId, _ItemBid, Count) of
%%                                {ok, Role1} -> {ok, Role1};
%%                                _ ->
%%                                    case sell_type(ItemVal) of
%%                                        {99, _} ->
%%                                            {error, ?T("物品无法出售")};
%%                                        {1, Val} ->
%%                                            DeleteItemIds = [{ItemId1, Count1} || {ItemId1, _, Count1} <- ItemInfos2],
%%                                            case role_gain:do([#loss{label = item_id, val = DeleteItemIds}], Role) of
%%                                                {ok, Role1} ->
%%                                                    Value = Val * Count,
%%                                                    case role_gain:do_notice([#gain{label = silver, val = Value}], Role1) of
%%                                                        {ok, Role2} ->
%%                                                            {ok, Role2};
%%                                                        _Err ->
%%                                                            ?DEBUG("添加石币失败:~w", [_Err]),
%%                                                            {false, ?T("物品贩卖石币失败")}
%%                                                    end;
%%                                                {false, _L} ->
%%                                                    {false, ?T("礼包数量不足, 无法使用")}
%%                                            end;
%%                                        {2, Val} ->
%%                                            DeleteItemIds = [{ItemId1, Count1} || {ItemId1, _, Count1} <- ItemInfos2],
%%                                            case role_gain:do([#loss{label = item_id, val = DeleteItemIds}], Role) of
%%                                                {ok, Role1} ->
%%                                                    Value = Val * Count,
%%                                                    case role_gain:do_notice([#gain{label = gold, val = Value}], Role1) of
%%                                                        {ok, Role2} ->
%%                                                            {ok, Role2};
%%                                                        _Err ->
%%                                                            ?DEBUG("添加金贝失败:~w", [_Err]),
%%                                                            {false, ?T("物品贩卖金贝失败")}
%%                                                    end;
%%                                                {false, _L} ->
%%                                                    {false, ?T("礼包数量不足, 无法使用")}
%%                                            end;
%%                                        {3, _V} ->
%%                                            case market_gold:sold(Role, [{ItemId, Count}]) of
%%                                                {ok, NewRole} ->
%%                                                    {ok, NewRole};
%%                                                _R ->
%%                                                    ?ERR("出售物品到金币市场失败,原因:~w", [_R]),
%%                                                    {false, ?T("出售失败")}
%%                                            end;
%%                                        {4, Val} ->
%%                                            Limit = 3,
%%                                            SelledNum = get_jade_sell_num(Role, ItemBid),
%%                                            case SelledNum + Count > Limit of
%%                                                true ->
%%                                                    ?ERR("[~ts]出售钻石物品ID:~w 数量:~w, 已出售数量: ~w, 超过每天最大出售限制(~w个)!!请检查产出是否有问题!", [Role#role.name, ItemBid, Count, SelledNum, Limit]),
%%                                                    {error, util:format(?T("每天最多出售~w个哦"), [Limit])};
%%                                                false ->
%%                                                    DeleteItemIds = [{ItemId1, Count1} || {ItemId1, _, Count1} <- ItemInfos2],
%%                                                    case role_gain:do([#loss{label = item_id, val = DeleteItemIds}], Role) of
%%                                                        {ok, Role1} ->
%%                                                            Value = Val * Count,
%%                                                            case role_gain:do_notice([#gain{label = jade, val = Value}], Role1) of
%%                                                                {ok, Role2} ->
%%                                                                    Role3 = add_jade_sell_num(Role2, ItemBid, Count),
%%                                                                    {ok, Role3};
%%                                                                _Err ->
%%                                                                    ?DEBUG("添加钻石失败:~w", [_Err]),
%%                                                                    {false, ?T("物品贩卖钻石失败")}
%%                                                            end;
%%                                                        {false, _L} ->
%%                                                            {false, ?T("礼包数量不足, 无法使用")}
%%                                                    end
%%                                            end;
%%                                        _ ->
%%                                            {error, ?T("贩卖类型配置异常")}
%%                                    end
%%                            end;
%%                        Err ->
%%                            Err
%%                    end;
%%                _ ->
%%                    {error, ?T("绑定物品无法出售")}
%%            end;
%%        _ ->
%%            {error, ?T("校验物品数据异常")}
%%    end.
%%
%%
%%sell_check(#item{type = _Type}) -> {ok}.
%%
%%sell_type([]) -> {99, 0};
%%sell_type([_ | L]) ->
%%    sell_type(L).
%%
%%%% @hidden
%%%% @doc 修改物品列表拓展字段的接口（替换）
%%
%%set_extra_list(Key, Val, Item) ->
%%    set_extra_list(Key, Val, "", Item).
%%
%%set_extra_list(Key, Val, Msg, Item = #item{extra = ExtraList}) ->
%%    Item#item{extra = set_extra_list(Key, Val, Msg, ExtraList)};
%%
%%set_extra_list(Key, Val, Msg, ExtraList) ->
%%    case lists:keyfind(Key, 1, ExtraList) of
%%        false -> [{Key, Val, Msg} | ExtraList];
%%        _ ->
%%            lists:keyreplace(Key, 1, ExtraList, {Key, Val, Msg})
%%    end.
%%
%%
%%%% @hidden
%%%% @doc 删除物品拓展列表的一个拓展值
%%del_extra_list(Key, ExtraList) ->
%%    lists:keydelete(Key, 1, ExtraList).
%%
%%find_extra_list(Key, ExtraList, Def) ->
%%    case lists:keyfind(Key, 1, ExtraList) of
%%        false -> Def;
%%        {_, Val, _} ->
%%            Val
%%    end.
%%
%%
%%
%%%% 根据物品购买来源获取价格
%%get_item_price([], _Role, Acc) -> Acc;
%%get_item_price([{BaseId, Num} | T], Role, Acc) ->
%%    Priority = item:attr(buy_source, BaseId),
%%    ?DEBUG("购买来源:~w", [Priority]),
%%    case role_gain:get_item_price_to_assets(Priority, BaseId, Role) of
%%        {ok, AssetsType, Price} ->
%%            get_item_price(T, Role, [{BaseId, Num, AssetsType, Price * Num} | Acc]);
%%        _R ->
%%            get_item_price(T, Role, [{BaseId, Num, 0, 0} | Acc])
%%    end.
%%
%%get_item_name(ItemBid) ->
%%    case item_data:get(ItemBid) of
%%        #item_base{name = Name} ->
%%            Name;
%%        _ ->
%%            ""
%%    end.
%%
%%
%%auto_buy_pellet(L = [{BaseId, _Num}], ItemAcc = [{BaseId, _Num1}], Role) ->
%%    Args = #{item_base_id_auto_buy => ?true},
%%    NL = format:val_to_loss(L, Args),
%%    case role_gain:item_base_id_to_assets(L, Role, [], [], [], [], []) of
%%        {ok, AssetsLoss1, MarketEffect, _LogItems, ShopBuys, MsgList} ->
%%            AssetsLoss = role_gain:merge_assets_loss(AssetsLoss1, []),
%%            Loss = case ItemAcc of
%%                       [] -> AssetsLoss;
%%                       [{_, 0}] ->
%%                           AssetsLoss;
%%                       _ ->
%%                           ItemLoss = NL#loss{label = item_base_id, val = ItemAcc},
%%                           [ItemLoss | AssetsLoss]
%%                   end,
%%            NG = format:val_to_gain(L),
%%            case role_gain:do(Loss ++ NG, Role) of
%%                {ok, NewRole} ->
%%                    shop_mgr:update_ets_auto_buy(ShopBuys, NewRole),
%%                    NewRole1 = market:auto_buy_effect(MarketEffect, NewRole),
%%                    [notice:send(NewRole1, ?notice_up, Notice) || Notice <- MsgList],
%%                    {ok, NewRole1};
%%                False ->
%%                    False
%%            end;
%%        {false, Msg} when is_list(Msg) ->
%%            {false, NL#loss{msg = Msg}};
%%        _False -> {false, NL}
%%    end.
%%
%%%% ===========================================
%%%% @doc 物品合成
%%%% ===========================================
%%%% 先合成非绑定 再合成绑定
%%item_compose(Role, ItemBid, 0, AutoBuy, 0) -> %% 合成一个
%%    case item_data:get_compose_item({ItemBid, 1}) of
%%        ComposeData = #item_compose_data{cost = ItemList, assets = AssetsList, rate = Rate, is_bind = CertainBind} ->
%%%%            {ItemList, AssetsList} = diff_item_assets(CostList, [], []),
%%            case compose_lev_check(Role, ComposeData) of
%%                {ok} ->
%%                    Count = 1,
%%                    AssetsList1 = [{AssetsId, Num * Count} || {AssetsId, Num} <- AssetsList],
%%                    case role_gain:do(format:val_to_loss(AssetsList1), Role) of
%%                        {ok, Role2} ->
%%                            %% 尝试合成非绑定物品
%%                            case item_compose_do(Role2, ItemBid, 0, Count, ItemList, Rate, AutoBuy, CertainBind) of
%%                                {ok, Role3, All, Num, ItemBid, AddL} ->
%%                                    {ok, Role3, All, Num, ItemBid, AddL};
%%                                _ -> %% 非绑定物品不足，尝试合成绑定物品
%%                                    case item_compose_do(Role2, ItemBid, 1, Count, ItemList, Rate, AutoBuy, CertainBind) of
%%                                        {ok, Role3, All, Num, ItemBid, AddL} ->
%%                                            {ok, Role3, All, Num, ItemBid, AddL};
%%                                        _Ret -> %% 绑定物品不足，混合合成
%%                                            item_compose_one(Role2, ItemBid, ItemList)
%%                                    end
%%                            end;
%%                        _ ->
%%                            {false, ?T("合成消耗资产不足")}
%%                    end;
%%                ERR1 ->
%%                    ERR1
%%            end;
%%        _ ->
%%            {false, ?T("物品合成材料不足")}
%%    end;
%%%% 先合成非绑定 再合成绑定
%%item_compose(Role, ItemBid, 0, AutoBuy, ?true) -> %% 合成所有
%%    case item_data:get_compose_item({ItemBid, 1}) of
%%        ComposeData = #item_compose_data{cost = ItemList, assets = AssetsList, rate = Rate, is_bind = CertainBind} ->
%%%%            {ItemList, AssetsList} = diff_item_assets(CostList, [], []),
%%            case compose_lev_check(Role, ComposeData) of
%%                {ok} ->
%%                    NoBindCount = find_count(ItemList, Role, 0, []),
%%                    BindCount = find_count(ItemList, Role, 1, []),
%%                    Count = NoBindCount + BindCount,
%%                    AssetsList1 = [{AssetsId, Num * Count} || {AssetsId, Num} <- AssetsList],
%%                    case role_gain:do(format:val_to_loss(AssetsList1), Role) of
%%                        {ok, Role2} ->
%%                            %% 尝试合成非绑定物品
%%                            case item_compose_do(Role2, ItemBid, 0, NoBindCount, ItemList, Rate, AutoBuy, CertainBind) of
%%                                {ok, Role3, All, Num, ItemBid, AddL} ->
%%                                    %% 非绑定物品合成成功后，尝试合成绑定物品
%%                                    case item_compose_do(Role3, ItemBid, 1, BindCount, ItemList, Rate, AutoBuy, CertainBind) of
%%                                        {ok, Role4, All1, Num1, ItemBid, AddL1} ->
%%                                            %% 绑定物品合成成功后，尝试混合合成
%%                                            case item_compose_one(Role4, ItemBid, ItemList) of
%%                                                {ok, Role5, All2, Num2, ItemBid, AddL2} ->
%%                                                    {ok, Role5, All + All1 + All2, Num + Num1 + Num2, ItemBid, AddL ++ AddL1 ++ AddL2};
%%                                                _ ->
%%                                                    {ok, Role4, All + All1, Num + Num1, ItemBid, AddL ++ AddL1}
%%                                            end;
%%                                        _Ret -> %% 绑定物品合成失败后，尝试混合合成
%%                                            case item_compose_one(Role3, ItemBid, ItemList) of
%%                                                {ok, Role4, All1, Num1, ItemBid, AddL1} ->
%%                                                    {ok, Role4, All + All1, Num + Num1, ItemBid, AddL ++ AddL1};
%%                                                _ ->
%%                                                    {ok, Role3, All, Num, ItemBid, AddL}
%%                                            end
%%                                    end;
%%                                _ -> %% 非绑定物品合成失败后，尝试合成绑定物品
%%                                    case item_compose_do(Role2, ItemBid, 1, BindCount, ItemList, Rate, AutoBuy, CertainBind) of
%%                                        {ok, Role3, All1, Num1, ItemBid, AddL1} ->
%%                                            %% 绑定物品合成成功后，尝试混合合成
%%                                            case item_compose_one(Role3, ItemBid, ItemList) of
%%                                                {ok, Role4, All2, Num2, ItemBid, AddL2} ->
%%                                                    {ok, Role4, All1 + All2, Num1 + Num2, ItemBid, AddL1 ++ AddL2};
%%                                                _ ->
%%                                                    {ok, Role3, All1, Num1, ItemBid, AddL1}
%%                                            end;
%%                                        _Ret ->
%%                                            %% 绑定物品合成失败后，尝试混合合成
%%                                            item_compose_one(Role2, ItemBid, ItemList)
%%%%                                            Ret
%%                                    end
%%                            end;
%%                        _ ->
%%                            {false, ?T("合成消耗资产不足")}
%%                    end;
%%                ERR1 ->
%%                    ERR1
%%            end;
%%        _ ->
%%            {false, ?T("物品合成材料不足")}
%%    end;
%%%% 合成非绑定物品
%%item_compose(Role, ItemBid, Type, AutoBuy, OneOrAll) when Type =:= ?true ->
%%    IsBind = 0,
%%    case item_data:get_compose_item({ItemBid, 1}) of
%%        ComposeData = #item_compose_data{cost = ItemList, assets = AssetsList, rate = Rate, is_bind = CertainBind} ->
%%%%            {ItemList, AssetsList} = diff_item_assets(CostList, [], []),
%%            case compose_lev_check(Role, ComposeData) of
%%                {ok} ->
%%                    Count = case OneOrAll of
%%                                ?true ->
%%                                    find_count(ItemList, Role, IsBind, []);
%%                                ?false ->
%%                                    1
%%                            end,
%%                    AssetsList1 = [{AssetsId, Num * Count} || {AssetsId, Num} <- AssetsList],
%%                    case role_gain:do(format:val_to_loss(AssetsList1), Role) of
%%                        {ok, Role2} ->
%%                            item_compose_do(Role2, ItemBid, IsBind, Count, ItemList, Rate, AutoBuy, CertainBind);
%%                        _ ->
%%                            {false, ?T("合成消耗资产不足")}
%%                    end;
%%                ERR1 ->
%%                    ERR1
%%            end;
%%        _ ->
%%            {false, ?T("物品合成材料不足")}
%%    end.
%%
%%%% 物品合成 可指定数量
%%item_compose(Role, ItemBid, NeedNum, 0) when NeedNum >= 1 ->
%%    case item_data:get_fun_type(ItemBid) == 2 of
%%        false ->
%%            {false, ?T("不合法的合成公式类型")};
%%        _ ->
%%            case item_data:get_compose_item({ItemBid, 2}) of
%%                ComposeData = #item_compose_data{} ->
%%                    case compose_lev_check(Role, ComposeData) of
%%                        {ok} ->
%%                            item_compose_do_1(ItemBid, NeedNum, Role);
%%                        ERR1 ->
%%                            ERR1
%%                    end;
%%                _ ->
%%                    {false, ?T("物品找不到合成公式")}
%%            end
%%    end;
%%%% 只合成非绑定物品
%%item_compose(Role, ItemBid, NeedNum, 1) when NeedNum >= 1 ->
%%    case item_data:get_fun_type(ItemBid) == 2 of
%%        false ->
%%            {false, ?T("不合法的合成公式类型")};
%%        _ ->
%%            case item_data:get_compose_item({ItemBid, 2}) of
%%                ComposeData = #item_compose_data{} ->
%%                    case compose_lev_check(Role, ComposeData) of
%%                        {ok} ->
%%                            %% 获取非绑定合成数量
%%                            case get_compose_count(item_data:get_class_id(ItemBid), Role, ItemBid, 0) of
%%                                {false, Msg} ->
%%                                    {false, Msg};
%%                                {NoBind, _NoBindRem} when NoBind >= NeedNum ->
%%                                    case item_compose_do(Role, [{ItemBid, NeedNum}], 0) of
%%                                        {false, Msg} ->
%%                                            {false, Msg};
%%                                        {true, ItemLoss, AssetsLoss} ->
%%                                            ItemLoss1 = [#loss{label = item_base_bind_id, val = [ItemLossData]} || ItemLossData <- ItemLoss],
%%                                            AssetsLoss1 = format:val_to_loss(AssetsLoss),
%%                                            Loss = ItemLoss1 ++ AssetsLoss1,
%%                                            case role_gain:do(Loss, Role) of
%%                                                {ok, Role1} ->
%%                                                    Gain = format:val_to_gain([{ItemBid, 0, NeedNum}]),
%%                                                    case role_gain:do(Gain, Role1) of
%%                                                        {ok, Role2} ->
%%                                                            {ok, Role2};
%%                                                        _ ->
%%                                                            {false, ?T("背包已满，请先清理背包")}
%%                                                    end;
%%                                                #loss{msg = Msg} ->
%%                                                    {false, Msg}
%%                                            end
%%                                    end;
%%                                _NoBind ->
%%                                    {false, ?T("物品合成材料不足")}
%%                            end;
%%                        ERR1 ->
%%                            ERR1
%%                    end;
%%                _ ->
%%                    {false, ?T("物品找不到合成公式")}
%%            end
%%    end;
%%item_compose(_, _, _, _) ->
%%    {false, ?T("合成数量必须大于1")}.
%%
%%%% 合成执行函数
%%item_compose_do_1(ItemBid, NeedNum, Role) ->
%%    ClassId = item_data:get_class_id(ItemBid),
%%    case get_compose_count(ClassId, Role, ItemBid, 0) of
%%        {false, Msg} ->
%%            {false, Msg};
%%        {NoBind, NoBindRem} ->
%%            case get_compose_count(ClassId, Role, ItemBid, 1) of
%%                {false, Msg} ->
%%                    {false, Msg};
%%                {Bind, BinRem} ->
%%                    EnoughOneOr = NoBindRem + BinRem >= get_one_compose_val(ClassId, ItemBid),
%%                    if
%%                    %% 即便合成数减一，也不够的话，即便补足，也不够
%%                        NoBind + Bind < NeedNum - 1 ->
%%                            {false, ?T("物品合成材料不足")};
%%                    %% 刚好是合成数减一，但是补足的数量不够
%%                        NoBind + Bind == NeedNum - 1 andalso not EnoughOneOr ->
%%                            {false, ?T("物品合成材料不足")};
%%                    %% 可以合成
%%                        true ->
%%                            {Loss, Gain} = calc_compose_count(Role, ItemBid, NeedNum, NoBind, Bind),
%%                            Reg =
%%                                case {Loss, Gain} of
%%                                    {false, Msg1} ->
%%                                        {false, Msg1};
%%                                    {[], []} ->
%%                                        {ok, Role};
%%                                    _ ->
%%                                        case role_gain:do(Loss, Role) of
%%                                            {ok, Role1} ->
%%                                                Gain1 = format:val_to_gain(Gain),
%%                                                case role_gain:do(Gain1, Role1) of
%%                                                    {ok, Role2} ->
%%                                                        %% 最后进行补足判断
%%                                                        {ok, Role2};
%%                                                    _ ->
%%                                                        {false, ?T("背包已满，请先清理背包")}
%%                                                end;
%%                                            {false, #loss{msg = Reason}} ->
%%                                                {false, Reason}
%%                                        end
%%                                end,
%%                            case Reg of
%%                                {false, R} ->
%%                                    {false, R};
%%                                {ok, Role3} ->
%%                                    if
%%                                        NoBind + Bind == NeedNum - 1 ->
%%                                            item_compose_one(Role3, ItemBid);
%%                                        true ->
%%                                            {ok, Role3}
%%                                    end
%%                            end
%%                    end
%%            end;
%%        _Err ->
%%            {false, ?T("错误的")}
%%    end.
%%
%%calc_compose_count(Role, ItemBid, NeedNum, NoBind, Bind) ->
%%    if
%%    %% 非绑定的材料少于需要的材料，需要进行补足
%%        NoBind < NeedNum andalso NoBind > 0 ->
%%            case item_compose_do(Role, [{ItemBid, NoBind}], 0) of
%%                {false, Msg} ->
%%                    {false, Msg};
%%                {true, ItemLoss, AssetsLoss} ->
%%                    ItemLoss1 = [#loss{label = item_base_bind_id, val = [ItemLossData]} || ItemLossData <- ItemLoss],
%%                    AssetsLoss1 = format:val_to_loss(AssetsLoss),
%%                    Bind1 =
%%                        if
%%                            NeedNum - NoBind >= Bind -> Bind;
%%                            true -> NeedNum - NoBind
%%                        end,
%%                    case item_compose_do(Role, [{ItemBid, Bind1}], 1) of
%%                        {false, Msg} ->
%%                            {false, Msg};
%%                        {true, ItemLoss2, AssetsLoss2} ->
%%                            ItemLoss3 = [#loss{label = item_base_bind_id, val = ItemLoss2}],
%%                            AssetsLoss3 = format:val_to_loss(AssetsLoss2),
%%                            {ItemLoss1 ++ AssetsLoss1 ++ ItemLoss3 ++ AssetsLoss3,
%%                                [{ItemBid, 0, NoBind}, {ItemBid, 1, Bind1}]}
%%                    end
%%            end;
%%    %% 不存在非绑定的物品
%%        NoBind < NeedNum andalso NoBind =< 0 ->
%%            Bind1 = min(NeedNum, Bind),
%%            if
%%                Bind1 == 0 ->
%%                    {[], []};
%%                true ->
%%                    case item_compose_do(Role, [{ItemBid, Bind1}], 1) of
%%                        {false, Msg} ->
%%                            {false, Msg};
%%                        {true, ItemLoss, AssetsLoss} ->
%%                            ItemLoss1 = [#loss{label = item_base_bind_id, val = [ItemLossData]} || ItemLossData <- ItemLoss],
%%                            AssetsLoss1 = format:val_to_loss(AssetsLoss),
%%                            {ItemLoss1 ++ AssetsLoss1, [{ItemBid, 1, Bind1}]}
%%                    end
%%            end;
%%    %% 非绑定的材料多余需要扣除的材料
%%        true ->
%%            case item_compose_do(Role, [{ItemBid, NeedNum}], 0) of
%%                {false, Msg} ->
%%                    {false, Msg};
%%                {true, ItemLoss, AssetsLoss} ->
%%                    ItemLoss1 = [#loss{label = item_base_bind_id, val = [ItemLossData]} || ItemLossData <- ItemLoss],
%%                    AssetsLoss1 = format:val_to_loss(AssetsLoss),
%%                    {ItemLoss1 ++ AssetsLoss1, [{ItemBid, 0, NeedNum}]}
%%            end
%%    end.
%%
%%%% 合成一个
%%item_compose_one(Role, ItemBid) ->
%%    {Loss, Gain} =
%%        case item_compose_do(Role, [{ItemBid, 1}]) of
%%            {false, Msg} ->
%%                {false, Msg};
%%            {true, ItemLoss, AssetsLoss} ->
%%                ItemLoss1 = format:val_to_loss(ItemLoss),
%%                AssetsLoss1 = format:val_to_loss(AssetsLoss),
%%                {ItemLoss1 ++ AssetsLoss1, format:val_to_gain([{ItemBid, 0, 1}])}
%%        end,
%%    case {Loss, Gain} of
%%        {false, Msg1} ->
%%            {false, Msg1};
%%        _ ->
%%            case role_gain:do(Loss, Role) of
%%                {ok, Role1} ->
%%                    case role_gain:do(Gain, Role1) of
%%                        {ok, Role2} ->
%%                            {ok, Role2};
%%                        _ ->
%%                            {false, ?T("背包已满，请先清理背包")}
%%                    end;
%%                {false, #loss{msg = Reason}} ->
%%                    {false, Reason}
%%            end
%%    end.
%%
%%%% 获得可以合成的数量和剩余的的价值
%%get_compose_count(_, _, _, _) ->
%%    {false, ?T("未定义的计算类型")}.
%%
%%get_one_compose_val(_, _) ->
%%    {false, ?T("未定义的计算类型")}.
%%
%%
%%item_compose_do(Role, ItemBid, IsBind, Count, DelItemList, Rate, AutoBuy, CertainBind) ->
%%    DelItemList1 = compose_count(DelItemList, IsBind, Count, []),
%%    Label = util:if_true(AutoBuy =:= ?false, item_base_bind_id, item_base_bind_id_auto_buy),
%%    ItemType = item:attr(type, ItemBid),
%%    DelItemList2 = DelItemList1,
%%    case role_gain:do([#loss{label = NewLabel, val = DelItemList2}], Role) of
%%%%    case role_gain:do(Loss, Role) of
%%        {ok, Role1} ->
%%            Count1 = rand_count(Rate, Count, 0),
%%            Role2 = Role1,
%%            case Count1 of
%%                0 -> {false, Role2, Count};
%%                _ ->
%%                    IsCertainBind = util:if_true(CertainBind =:= ?true, CertainBind, IsBind),
%%                    case role_gain:auto_overlap([#gain{label = item_base_id, val = [{ItemBid, IsCertainBind, Count1}]}], Role2) of
%%                        {ok, Role3, _, _, _} ->
%%                            {ok, Role3, Count, Count1, ItemBid, []};
%%                        _ ->
%%                            {false, ?T("背包空间不足，请先清理背包哦")}
%%                    end
%%            end;
%%        _ERR ->
%%            {false, ?T("合成材料不足")}
%%    end.
%%
%%item_compose_do(Role, ItemL, IsBind) ->
%%    item_compose_do(Role, ItemL, IsBind, [], []).
%%
%%item_compose_do(Role, ItemL) ->
%%    item_compose_do(Role, ItemL, [], []).
%%
%%item_compose_do(_Role, [], _IsBind, ItemLoss, AssetsLoss) ->
%%    {true, ItemLoss, merge_same_item(AssetsLoss)};
%%item_compose_do(Role, [{ItemBid, Count} | T], IsBind, ItemLoss, AssetsLoss) ->
%%    case item_data:get_compose_item({ItemBid, 2}) of
%%        #item_compose_data{cost = ItemList, assets = AssetsList} ->
%%            ItemList1 = compose_count(ItemList, IsBind, Count, []),
%%            {NewNeed, NewItemLoss} = item_compose_do_f1(Role, IsBind, ItemList1, T, ItemLoss),
%%            item_compose_do(Role, NewNeed, IsBind, NewItemLoss, AssetsList ++ AssetsLoss);
%%        _ ->
%%            {false, ?T("合成材料不足")}
%%    end.
%%
%%item_compose_do_f1(_Role, _IsBind, [], NeedL, ItemLoss) ->
%%    {merge_same_item(NeedL), ItemLoss};
%%item_compose_do_f1(Role, IsBind, [{NeedItemId, _, NeedItemCount} | T], NeedL, ItemLoss) ->
%%    ItemNum = package:find_bind_num(NeedItemId, IsBind, bag, Role),
%%    if
%%        ItemNum =< 0 ->
%%            item_compose_do_f1(Role, IsBind, T, [{NeedItemId, NeedItemCount} | NeedL], ItemLoss);
%%        true ->
%%            case lists:keyfind(NeedItemId, 1, ItemLoss) of
%%                false ->
%%                    if
%%                        ItemNum >= NeedItemCount ->
%%                            item_compose_do_f1(Role, IsBind, T, NeedL, [{NeedItemId, IsBind, NeedItemCount} | ItemLoss]);
%%                        true ->
%%                            item_compose_do_f1(Role, IsBind, T, [{NeedItemId, NeedItemCount - ItemNum} | NeedL], [{NeedItemId, IsBind, ItemNum} | ItemLoss])
%%                    end;
%%                {NeedItemId, B, LossNum} ->
%%                    if
%%                        ItemNum == LossNum ->
%%                            item_compose_do_f1(Role, IsBind, T, [{NeedItemId, NeedItemCount} | NeedL], ItemLoss);
%%                        ItemNum - LossNum >= NeedItemCount ->
%%                            ItemLoss1 = lists:keyreplace(NeedItemId, 1, ItemLoss, {NeedItemId, B, LossNum + NeedItemCount}),
%%                            item_compose_do_f1(Role, IsBind, T, NeedL, ItemLoss1);
%%                        true ->
%%                            ItemLoss1 = lists:keyreplace(NeedItemId, 1, ItemLoss, {NeedItemId, B, ItemNum}),
%%                            item_compose_do_f1(Role, IsBind, T, [{NeedItemId, NeedItemCount - ItemNum + LossNum} | NeedL], ItemLoss1)
%%                    end
%%            end
%%    end.
%%
%%
%%item_compose_do(_Role, [], ItemLoss, AssetsLoss) ->
%%    {true, ItemLoss, merge_same_item(AssetsLoss)};
%%item_compose_do(Role, [{ItemBid, Count} | T], ItemLoss, AssetsLoss) ->
%%    case item_data:get_compose_item({ItemBid, 2}) of
%%        #item_compose_data{cost = ItemList, assets = AssetsList} ->
%%            ItemList1 = compose_count(ItemList, 0, Count, []),
%%            {NewNeed, NewItemLoss} = item_compose_do_f1(Role, ItemList1, T, ItemLoss),
%%            item_compose_do(Role, NewNeed, NewItemLoss, AssetsList ++ AssetsLoss);
%%        _ ->
%%            {false, ?T("合成材料不足")}
%%    end.
%%
%%item_compose_do_f1(_Role, [], NeedL, ItemLoss) ->
%%    {merge_same_item(NeedL), ItemLoss};
%%item_compose_do_f1(Role, [{NeedItemId, _, NeedItemCount} | T], NeedL, ItemLoss) ->
%%    item_compose_do_f1(Role, [{NeedItemId, NeedItemCount} | T], NeedL, ItemLoss);
%%item_compose_do_f1(Role, [{NeedItemId, NeedItemCount} | T], NeedL, ItemLoss) ->
%%    ItemNum = package:find_num(NeedItemId, bag, Role),
%%    if
%%        ItemNum =< 0 ->
%%            item_compose_do_f1(Role, T, [{NeedItemId, NeedItemCount} | NeedL], ItemLoss);
%%        true ->
%%            case lists:keyfind(NeedItemId, 1, ItemLoss) of
%%                false ->
%%                    if
%%                        ItemNum >= NeedItemCount ->
%%                            item_compose_do_f1(Role, T, NeedL, [{NeedItemId, NeedItemCount} | ItemLoss]);
%%                        true ->
%%                            item_compose_do_f1(Role, T, [{NeedItemId, NeedItemCount - ItemNum} | NeedL], [{NeedItemId, ItemNum} | ItemLoss])
%%                    end;
%%                {NeedItemId, LossNum} ->
%%                    if
%%                        ItemNum == LossNum ->
%%                            item_compose_do_f1(Role, T, [{NeedItemId, NeedItemCount} | NeedL], ItemLoss);
%%                        ItemNum - LossNum >= NeedItemCount ->
%%                            ItemLoss1 = lists:keyreplace(NeedItemId, 1, ItemLoss, {NeedItemId, LossNum + NeedItemCount}),
%%                            item_compose_do_f1(Role, T, NeedL, ItemLoss1);
%%                        true ->
%%                            ItemLoss1 = lists:keyreplace(NeedItemId, 1, ItemLoss, {NeedItemId, ItemNum}),
%%                            item_compose_do_f1(Role, T, [{NeedItemId, NeedItemCount - ItemNum + LossNum} | NeedL], ItemLoss1)
%%                    end
%%            end
%%    end.
%%
%%compose_lev_check(#role{lev = RoleLev}, #item_compose_data{open_lev = Lev}) ->
%%    case Lev == 0 orelse RoleLev >= Lev of
%%        true ->
%%            {ok};
%%        _ ->
%%            {false, ?T("角色等级不足")}
%%    end.
%%
%%item_compose_one(Role, ItemBid, ItemList) ->
%%    case check_num(ItemList, Role) of
%%        false -> {false, ?T("合成材料不足")};
%%        _ ->
%%            ItemType = item:attr(type, ItemBid),
%%            NewLabel = util:if_true(ItemType =:= ?item_type_pet_recruit orelse ItemType == ?item_type_pet_shenqi, item_base_id_pet_debris, item_base_id),
%%            case role_gain:do([#loss{label = NewLabel, val = ItemList}], Role) of
%%                {ok, Role1} ->
%%                    case role_gain:auto_overlap([#gain{label = item_base_id, val = [{ItemBid, 1, 1}]}], Role1) of
%%                        {ok, Role2, _, _, _} ->
%%                            {ok, Role2, 1, 1, ItemBid, []};
%%                        _ ->
%%                            {false, ?T("背包空间不足，请先清理背包哦")}
%%                    end;
%%                _ERR ->
%%                    {false, ?T("合成材料不足")}
%%            end
%%    end.
%%
%%check_num([], _R) -> true;
%%check_num([{ItemBid, Num} | L], Role) ->
%%    case package:count(by_base_id, ItemBid, Role#role.p_bag) of
%%        {_, Val} when Val >= Num -> check_num(L, Role);
%%        _ ->
%%            case package:count(by_base_id, ItemBid, Role#role.p_pet_debris) of
%%                {_, Val} when Val >= Num -> check_num(L, Role);
%%                _ -> false
%%            end
%%    end.
%%
%%
%%find_count([], _, _, CountList) ->
%%    Count = lists:min(CountList),
%%    max(1, Count);
%%find_count([{Bid, Count} | L], Role, IsBind, List) when Bid < ?assets_item_init_id orelse Bid > ?assets_item_end_id ->
%%    HaveCount =
%%        case item:attr(type, Bid) of
%%            ?item_type_pet_shenqi_chip ->
%%                package:find_bind_num(Bid, IsBind, p_pet_debris, Role);
%%            _ ->
%%                package:find_bind_num(Bid, IsBind, bag, Role)
%%        end,
%%    ItemCount = HaveCount div Count,
%%    find_count(L, Role, IsBind, [ItemCount | List]);
%%find_count([{AssetsId, Count} | L], Role, IsBind, List) ->
%%    HaveCount = role_gain:find_assets(Role, AssetsId),
%%    ItemCount = HaveCount div Count,
%%    find_count(L, Role, IsBind, [ItemCount | List]).
%%
%%compose_count([], _IsBind, _, List) -> List;
%%compose_count([{Bid, Value} | L], IsBind, Num, List) ->
%%    compose_count(L, IsBind, Num, [{Bid, IsBind, Value * Num} | List]).
%%
%%
%%rand_count(100, Count, _) -> Count;
%%rand_count(0, Count, _) -> Count;
%%rand_count(_Rate, 0, Count) -> Count;
%%rand_count(Rate, Count, Num) ->
%%    case Rate >= util:rand(1, 100) of
%%        true ->
%%            rand_count(Rate, Count - 1, Num + 1);
%%        false ->
%%            rand_count(Rate, Count - 1, Num)
%%
%%    end.
%%
%%%% 区分物品和资产
%%diff_item_assets([], ItemList, AssetsList) -> {ItemList, AssetsList};
%%diff_item_assets([{Bid, Val} | Items], ItemList, AssetsList) when Bid < ?assets_item_init_id orelse Bid > ?assets_item_end_id ->
%%    diff_item_assets(Items, [{Bid, Val} | ItemList], AssetsList);
%%diff_item_assets([{Bid, Val} | Items], ItemList, AssetsList) when Bid >= ?assets_item_init_id andalso Bid =< ?assets_item_end_id ->
%%    diff_item_assets(Items, ItemList, [{Bid, Val} | AssetsList]).
%%
%%%% 购买物品
%%buy_item(Role, Bid, Num) ->
%%    case item_data:get(Bid) of
%%        #item_base{} ->
%%            case get_item_price([{Bid, Num}], Role, []) of
%%                [{_, _Num, AssetsType, Cost}] when Cost > 0 ->
%%                    Loss = format:val_to_loss([{AssetsType, Cost}]),
%%                    Gain = format:val_to_gain([{Bid, 1, Num}]),
%%                    case role_gain:do_notice(Loss ++ Gain, Role) of
%%                        {ok, NRole} ->
%%                            ?DEBUG("添加物品成功"),
%%                            {ok, NRole};
%%                        {false, #loss{msg = Msg}} ->
%%                            {false, Msg};
%%                        {false, #gain{msg = Msg}} ->
%%                            {false, Msg}
%%                    end;
%%                _ ->
%%                    {false, ?T("找不到物品价格")}
%%            end;
%%        false ->
%%            {false, ?T("未找到该物品")}
%%    end.
%%
%%%%过滤0数量的道具
%%filter_zero_item(Items)->
%%    filter_zero_item(Items, []).
%%
%%filter_zero_item([], Items)->lists:reverse(Items);
%%filter_zero_item([{_BaseId, _Bind, 0}|T], Items)->
%%    filter_zero_item(T, Items);
%%filter_zero_item([{_BaseId, 0}|T], Items)->
%%    filter_zero_item(T, Items);
%%filter_zero_item([H|T], Items)->
%%    filter_zero_item(T, [H|Items]).
%%
%%%%合并奖励列表
%%%%相同绑定格式的合并在一起，不改变绑定方式
%%merge_reward(ItemList)->
%%    merge_reward(ItemList, []).
%%merge_reward([], List)->lists:reverse([{ItemBid,Bind,Num}||{{ItemBid,Bind},Num}<-List]);
%%merge_reward([{_ItemBid, _Bind, _Num = 0}|T], List)->
%%    merge_reward(T, List);
%%merge_reward([{_ItemBid, _Num = 0}|T], List)->
%%    merge_reward(T, List);
%%merge_reward([{ItemBid, Bind, Num}|T], List)->
%%    case lists:keyfind({ItemBid,Bind}, 1, List) of
%%        {_, Num2} ->
%%            merge_reward(T, lists:keyreplace({ItemBid,Bind}, 1, List, {{ItemBid,Bind},Num2+Num}));
%%        false ->
%%            merge_reward(T, [{{ItemBid,Bind},Num}|List])
%%    end;
%%merge_reward([{ItemBid,Num}|T], List)->
%%    case lists:keyfind({ItemBid,?false}, 1, List) of
%%        {_, Num2} ->
%%            merge_reward(T, lists:keyreplace({ItemBid,?false}, 1, List, {{ItemBid,?false},Num2+Num}));
%%        false ->
%%            merge_reward(T, [{{ItemBid,?false}, Num}|List])
%%    end.
%%
%%merge_same_item(ItemList) ->
%%    merge_same_item(ItemList, []).
%%
%%merge_same_item([], L) -> lists:reverse(L);
%%merge_same_item([{ItemBid, _Bind, Num} | T], L) ->
%%    case lists:keyfind(ItemBid, 1, L) of
%%        false ->
%%            merge_same_item(T, [{ItemBid, Num} | L]);
%%        {ItemBid, Count} ->
%%            merge_same_item(T, lists:keyreplace(ItemBid, 1, L, {ItemBid, Num + Count}))
%%    end;
%%merge_same_item([#item{base_id = ItemBid, quantity = Num} | T], L) ->
%%    case lists:keyfind(ItemBid, 1, L) of
%%        false ->
%%            merge_same_item(T, [{ItemBid, Num} | L]);
%%        {ItemBid, Count} ->
%%            merge_same_item(T, lists:keyreplace(ItemBid, 1, L, {ItemBid, Num + Count}))
%%    end;
%%merge_same_item([{ItemBid, Num} | T], L) ->
%%    case lists:keyfind(ItemBid, 1, L) of
%%        false ->
%%            merge_same_item(T, [{ItemBid, Num} | L]);
%%        {ItemBid, Count} ->
%%            merge_same_item(T, lists:keyreplace(ItemBid, 1, L, {ItemBid, Num + Count}))
%%    end.
%%
%%filter_same_item(ItemList) ->
%%    filter_same_item(ItemList, []).
%%
%%filter_same_item([], L) -> L;
%%filter_same_item([{ItemBid, _Bind, Num} | T], L) ->
%%    filter_same_item(T, [{ItemBid, Num} | L]);
%%filter_same_item([#item{base_id = ItemBid, quantity = Num} | T], L) ->
%%    filter_same_item(T, [{ItemBid, Num} | L]);
%%filter_same_item([{ItemBid, Num} | T], L) ->
%%    filter_same_item(T, [{ItemBid, Num} | L]).
%%
%%filter_classes_item([], _Classes, L) -> L;
%%filter_classes_item([Item = {_ItemBid, _Bind, _Num} | T], _Classes, L) ->
%%    filter_classes_item(T, _Classes, [Item | L]);
%%filter_classes_item([Item = {_ItemBid, _Num} | T], _Classes, L) ->
%%    filter_classes_item(T, _Classes, [Item | L]);
%%filter_classes_item([{ItemBid, Bind, Num, Classes} | T], Classes, L) ->
%%    filter_classes_item(T, Classes, [{ItemBid, Bind, Num} | L]);
%%filter_classes_item([_ | T], Classes, L) ->
%%    filter_classes_item(T, Classes, L).
%%
%%double_reward([], List, _Mul) -> List;
%%double_reward([{ItemBid, Bind, Num} | ItemList], NewList, Mul) ->
%%    double_reward(ItemList, [{ItemBid, Bind, util:round(Num * Mul)} | NewList], Mul);
%%double_reward([{ItemBid, Num} | ItemList], NewList, Mul) ->
%%    double_reward(ItemList, [{ItemBid, util:round(Num * Mul)} | NewList], Mul).
%%
%%%% 拆分发送奖励
%%send_reward(Role, ItemBidList, Title, Content) ->
%%    Args = #{title => Title, content => Content, items => ItemBidList},
%%    send_reward(Role, Args).
%%
%%send_reward(Role, ItemBidList, Title, Content, Ext) ->
%%    Args = #{title => Title, content => Content, items => ItemBidList, notice_ext => Ext},
%%    send_reward(Role, Args).
%%
%%send_reward(Role, Args) ->
%%    Title = maps:get(title, Args, ?T("")),
%%    Content = maps:get(content, Args, ?T("")),
%%    ItemBidList = maps:get(items, Args, []),
%%    NoticeTitle = maps:get(notice_title, Args, ?T("")),
%%    NoticeTail = maps:get(notice_tail, Args, ?T("")),
%%    NoticeExt = maps:get(notice_ext, Args, []),
%%    {ItemList, AssetsList} = holiday_lib:holiday_make_item(ItemBidList, make_holiday),
%%    case role_gain:do_notice(format:val_to_gain(AssetsList), Role, NoticeTitle, NoticeTail, NoticeExt) of
%%        {ok, Role1} ->
%%            case role_gain:do_notice(format:val_to_gain(ItemList), Role1, NoticeTitle, NoticeTail, NoticeExt) of
%%                {ok, Role2} ->
%%                    {ok, Role2};
%%                _ ->
%%                    notice:return(?T("背包空间不足，奖励通过邮件发送")),
%%                    case maps:get(from, Args, ?undefined) of
%%                        {FromFace, FromName} ->
%%                            mail:send(Role1, #{title => Title, content => Content, items => ItemList, from_name => FromName, from_face => FromFace});
%%                        _ ->
%%                            mail:send(Role1, #{title => Title, content => Content, items => ItemList})
%%                    end,
%%                    {ok, Role1}
%%            end;
%%        _ ->
%%            notice:return(?T("背包空间不足，奖励通过邮件发送")),
%%            case maps:get(from, Args, ?undefined) of
%%                {FromFace, FromName} ->
%%                    mail:send(Role, #{title => Title, content => Content, items => ItemList, from_name => FromName, from_face => FromFace});
%%                _ ->
%%                    mail:send(Role, #{title => Title, content => Content, items => ItemList})
%%            end,
%%            {ok, Role}
%%    end.
%%
%%send_reward_no_notice(Role, ItemBidList, Title, Content) ->
%%    Args = #{title => Title, content => Content, items => ItemBidList},
%%    send_reward_no_notice(Role, Args).
%%
%%send_reward_no_notice(Role, Args) ->
%%    Title = maps:get(title, Args, ?T("")),
%%    Content = maps:get(content, Args, ?T("")),
%%    ItemList = maps:get(items, Args, []),
%%    case role_gain:do(format:val_to_gain(ItemList), Role) of
%%        {ok, Role1} ->
%%            {ok, Role1};
%%        _ ->
%%            notice:return(?T("背包空间不足，奖励通过邮件发送")),
%%            case maps:get(from, Args, ?undefined) of
%%                {FromFace, FromName} ->
%%                    mail:send(Role, #{title => Title, content => Content, items => ItemList, from_name => FromName, from_face => FromFace});
%%                _ ->
%%                    mail:send(Role, #{title => Title, content => Content, items => ItemList})
%%            end,
%%            {ok, Role}
%%    end.
%%
%%check_class_id(_, _, _) ->
%%    true.
%%
%%%% 获取物品的数量
%%get_item_num(#role{p_bag = #package{items = Items}}, ItemBid) ->
%%    Fun =
%%        fun(#item{base_id = Bid, quantity = Quantity}, Acc) ->
%%            case Bid of
%%                ItemBid ->
%%                    Quantity + Acc;
%%                _ ->
%%                    Acc
%%            end
%%        end,
%%    lists:foldr(Fun, 0, Items).
%%
%%%%发送奖励通知
%%alert_reward([])->  %% 获得列表为空时不处理
%%    skip;
%%alert_reward(Reward1)->
%%    alert_reward(Reward1, []).
%%
%%alert_reward([], _Reward2)->
%%    skip;
%%alert_reward(Reward1, Reward2)->
%%    alert_reward(Reward1, Reward2, []).
%%
%%alert_reward([], _Reward2, _Reward3)->
%%    skip;
%%alert_reward(Reward1, Reward2, Reward3)->
%%    role:link_send(10352, {merge_same_item(Reward1), Reward2, Reward3}).
%%
%%%%发送奖励通知(不合并)
%%alert_reward_no_merge([])->  %% 获得列表为空时不处理
%%    skip;
%%alert_reward_no_merge(Reward1)->
%%    alert_reward_no_merge(Reward1, []).
%%
%%alert_reward_no_merge([], _Reward2)->
%%    skip;
%%alert_reward_no_merge(Reward1, Reward2)->
%%    alert_reward_no_merge(Reward1, Reward2, []).
%%
%%alert_reward_no_merge([], _Reward2, _Reward3)->
%%    skip;
%%alert_reward_no_merge(Reward1, Reward2, Reward3)->
%%    role:link_send(10352, {filter_same_item(Reward1), Reward2, Reward3}).
%%%% 物品品质名称
%%to_quality_name(#item{quality = Quality}) ->
%%    case Quality of
%%        ?quality_white ->
%%            ?T("白");
%%        ?quality_green ->
%%            ?T("绿");
%%        ?quality_blue ->
%%            ?T("蓝");
%%        ?quality_purple ->
%%            ?T("紫");
%%        ?quality_orange ->
%%            ?T("橙");
%%        ?quality_red ->
%%            ?T("红");
%%        ?quality_gold ->
%%            ?T("金");
%%        _ ->
%%            ?T("白")
%%    end.